package com.mxchip.livestar.av.camera;

import android.graphics.SurfaceTexture;

import androidx.annotation.NonNull;

import com.mxchip.livestar.av.player.PreviewOnSurfaceCreatedHandler;
import com.mxchip.livestar.ui.call.AVDevice;
import com.videohigh.camera.h1.DualStreamCamera;
import com.videohigh.camera.h1.H264DataCallback;

public class CameraHandle implements PreviewOnSurfaceCreatedHandler {

    private static final String TAG = "CameraHandle";

    private static CameraHandle mInstance = new CameraHandle();

    public static synchronized CameraHandle getInstance() {
        return mInstance;
    }

    public void openAndStartPreview(SurfaceTexture surfaceTexture) {
        DualStreamCamera.getInstance().start(surfaceTexture, dualCameraCallback);
    }

    private H264DataCallback dualCameraCallback = new H264DataCallback() {
        @Override
        public void getH264Data(@NonNull byte[] data, int length, int width, int height) {
            if(mEncoderCallback != null) {
                mEncoderCallback.onH264FramePacket(data, DEVICE_SMALL_NAME, width, height, 0, System.currentTimeMillis());
            }
        }

        @Override
        public void getH264Data2(@NonNull byte[] data, int length, int width, int height) {
            if(mEncoderCallback != null) {
                mEncoderCallback.onH264FramePacket(data, DEVICE_NAME, width, height, 0, System.currentTimeMillis());
            }
        }
    };

    /*public void startPreview() {
        if (mCamera != null) {
            try {
                mCamera.setPreviewTexture(surfaceTexture);
            } catch (IOException e) {
                e.printStackTrace();
            }
            mCamera.startPreview();
        }
    }

    public void stopPreview() {
        if (mCamera != null) {
            try {
                mCamera.setPreviewCallback(null);
                mCamera.stopPreview();
            } catch (Exception e) {
                Log.e(TAG, "Tried to stop a non-existant preview. Ignoring");
                e.printStackTrace();
            }
        }
    }*/

    public void releaseCamera() {
        DualStreamCamera.getInstance().stop();
        mEncoderCallback = null;
    }

    public boolean isCameraOpen() {
        return DualStreamCamera.getInstance().isCameraOpen();
    }


    public static final String DEVICE_NAME = AVDevice.CAMERA_LOCAL;
    public static final String DEVICE_SMALL_NAME = AVDevice.CAMERA_LOCAL_SMALL;

    private EncoderCallback mEncoderCallback;

    public void setEncoderCallback(EncoderCallback encoderCallback) {
        this.mEncoderCallback = encoderCallback;
    }

    public void setEncoderBitRate(int bitRate) {
        DualStreamCamera.getInstance().setEncoderBitrate(bitRate);
    }

    public void setEncoderSmallBitRate(int bitRate) {
        DualStreamCamera.getInstance().setEncoderSmallBitRate(bitRate);
    }
}
